package com.jfzt;

import co.elastic.clients.elasticsearch._types.HealthStatus;
import co.elastic.clients.elasticsearch.cat.CatRequestBase;
import co.elastic.clients.elasticsearch.cat.HealthRequest;
import co.elastic.clients.elasticsearch.cat.HealthResponse;
import co.elastic.clients.elasticsearch.cat.health.HealthRecord;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jfzt.pojo.ESHealthCheck;
import com.jfzt.pojo.GroupUserVO;
import com.jfzt.utils.JsonUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.cluster.ClusterHealth;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author: shunpeng.hu
 * @date: 2024/1/8 15:40
 */
@SpringBootTest
public class SpringbootTest02 {

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
        ));
    }

    @Order(value = 1)
    @Test
    @DisplayName("创建索引库")
    public void testCreateIndex() throws IOException {
        // 创建Request对象
        CreateIndexRequest request = new CreateIndexRequest("loginv2");

        // 添加请求参数，定义了静态字符串常量MAPPING_TEMPLATE
        request.source("{" +
                "  \"kcAdmin\": \"admin.test\"," +
                "  \"kcClient\": \"后端\"," +
                "  \"kcPassword\": \"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWRlMGU0ZmVjMDk0MjM1YTJmMjk5MTgwNThkMDA0OSIsInN1YiI6ImpmenQudGVzdCIsImlzcyI6ImFkbWluIiwiaWF0IjoxNjk3MDA4OTE3LCJleHAiOjE3MTI1NjA5MTd9.vLr_K_QSAXonSTXkmjkeLzQVwjew-HG3tZiPhDALV3o\"," +
                "  \"kcRealm\": \"Test\"" +
                "}", XContentType.JSON);

        //发送请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    public void testUpdateIndex() {

    }

    @Order(value = 2)
    @Test
    @DisplayName("创建索引文档")
    public void testCreateDocument() throws IOException {
        //创建Request对象
        IndexRequest indexRequest = new IndexRequest("loginv2").id("1");
        //准备请求参数
        IndexRequest request = indexRequest.source("{" +
                "  \"kcAdmin\": \"admin.test\"," +
                "  \"kcClient\": \"后端\"," +
                "  \"kcPassword\": \"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWRlMGU0ZmVjMDk0MjM1YTJmMjk5MTgwNThkMDA0OSIsInN1YiI6ImpmenQudGVzdCIsImlzcyI6ImFkbWluIiwiaWF0IjoxNjk3MDA4OTE3LCJleHAiOjE3MTI1NjA5MTd9.vLr_K_QSAXonSTXkmjkeLzQVwjew-HG3tZiPhDALV3o\"," +
                "  \"kcRealm\": \"Test\"," +
                "  \"RequestDate\": \"2024-01-31 09:53:46.117\"" +
                "}", XContentType.JSON);

        //发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    @Order(value = 3)
    @Test
    @DisplayName("查询索引文档")
    public void testQueryIndex() {
        String indexName = "groupv2";

        SearchRequest getIndexRequest = new SearchRequest();
        try {
            getIndexRequest.indices(indexName);
//            getIndexRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));

            //match搜索匹配查询
            getIndexRequest.source(new SearchSourceBuilder().
                    query(QueryBuilders.matchQuery("kcAdmin", "admin.test"))
                    .trackTotalHits(true)
                    .from(0)
                    .size(20));

            // term精确匹配查询
            getIndexRequest.source(new SearchSourceBuilder()
                    .query(QueryBuilders.termQuery("kcAdmin", "admin.test")).from(0).size(20));

//            getIndexRequest.source(new SearchSourceBuilder().query(QueryBuilders
//                    .fuzzyQuery("kcAdmin","admin").fuzziness(Fuzziness.ONE)));

            // 匹配查询所有
//            getIndexRequest.source(new SearchSourceBuilder()
//                    .query(QueryBuilders.matchAllQuery()).from(0).size(15));

//            getIndexRequest.source(new SearchSourceBuilder().query(QueryBuilders.boolQuery()
//                    .should(QueryBuilders.matchQuery("kcAdmin", "admin"))
//                    .should(QueryBuilders.matchQuery("kcClient", "后端"))));

//            getIndexRequest.source(new SearchSourceBuilder().query(QueryBuilders.boolQuery()
//                    .must(QueryBuilders.matchQuery("kcAdmin", "admin.test"))
//                    .must(QueryBuilders.rangeQuery("RequestDate", "2024-01-31 09:53:46.117"))
//                    ).trackTotalHits(true)
//                    .from(0)
//                    .size(20)
//            );

            SearchResponse response = client.search(getIndexRequest, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits()) {
//                System.out.println("hit.getSourceAsMap() = " + hit.getSourceAsMap());
//                Object requestBody = hit.getSourceAsMap().get("data");
                Object data = hit.getSourceAsMap().get("data");
                if (data != null) {
                    System.out.println("hit.getSourceAsMap().get(\"RequestBody\") = " + hit.getSourceAsMap().get("data").toString().contains("["));
                    List<GroupUserVO> list = JSONArray.parseArray(JSON.toJSONString(hit.getSourceAsMap().get("data")), GroupUserVO.class);

                    for (GroupUserVO groupUserVO : list) {
                        System.out.println(groupUserVO);
                    }
                }
                System.out.println("hit.getSourceAsMap().get(\"RequestBody\") = " + hit.getSourceAsMap().get("data"));

            }

//            for (SearchHit hit : response.getHits().getHits()) {
//                System.out.println("hit.getSourceAsMap().values() = " + hit.getSourceAsMap().values());
//            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Order(value = 4)
    @Test
    @DisplayName("批量请求导入文档")
    public void testBulk() {
        try {
            //1. 创建BulkRequest对象
            BulkRequest request = new BulkRequest();

            //2. 批处理提交请求的参数
            request.add(
                    new IndexRequest("loginv2").id("2").source("{" +
                            "\"kcAdmin\": \"admin.test\"," +
                            "\"kcClient\": \"后端\"," +
                            "\"kcPassword\": \"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWRlMGU0ZmVjMDk0MjM1YTJmMjk5MTgwNThkMDA0OSIsInN1YiI6ImpmenQudGVzdCIsImlzcyI6ImFkbWluIiwiaWF0IjoxNjk3MDA4OTE3LCJleHAiOjE3MTI1NjA5MTd9.vLr_K_QSAXonSTXkmjkeLzQVwjew-HG3tZiPhDALV3o\"," +
                            "\"kcRealm\": \"Test\"" +
                            "}", XContentType.JSON));

            request.add(new IndexRequest("loginv2").id("3").source("{" +
                    "    \"kcAdmin\": \"admin.test\"," +
                    "    \"kcClient\": \"后端\"," +
                    "    \"kcPassword\": \"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWRlMGU0ZmVjMDk0MjM1YTJmMjk5MTgwNThkMDA0OSIsInN1YiI6ImpmenQudGVzdCIsImlzcyI6ImFkbWluIiwiaWF0IjoxNjk3MDA4OTE3LCJleHAiOjE3MTI1NjA5MTd9.vLr_K_QSAXonSTXkmjkeLzQVwjew-HG3tZiPhDALV3o\"," +
                    "    \"kcRealm\": \"Test\"" +
                    "}", XContentType.JSON));


            //3. 发起.bulk请求
            client.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Order(value = 5)
    @Test
    @DisplayName(value = "测试健康状态")
    public void testESHealth() {
        try {
            Request request = new Request("GET", "/_cat/health?v");

            Response response = client.getLowLevelClient().performRequest(request);

//            String responseEntity = EntityUtils.toString(response.getEntity());


//            String url = ESProfileConfig.ES_APPLICATION_URL;
//            MediaType mediaType = MediaType.parse("application/json");
//            Request request = new Request.Builder().url(url).get()
//                    .addHeader("Content-Type", "application/json").build();
//            Response response = okHttpClient.newCall(request).execute();
//            String s = Objects.requireNonNull(response.body()).string();

//
        RestTemplate restTemplate = new RestTemplate();
        String url="http://localhost:9200/_cat/health?v";

        HealthRecord healthCheck = restTemplate.getForObject(url, HealthRecord.class);
//        HealthRecord yellow = new HealthRecord.Builder().status("yellow").build();


//            String result=yellow.status().equals("yellow")?"ES在线":"ES宕机";
//            ClusterHealthRequest healthRequest = new HealthRequest.Builder().build();
//            ClusterHealthRequest clusterHealthRequest = new ClusterHealthRequest();
//
//            ClusterHealthResponse healthResponse = client.cluster().health(clusterHealthRequest, RequestOptions.DEFAULT);
//            ClusterHealthStatus status = healthResponse.getStatus();
//
//
//            System.out.println(status);

////            System.out.println(Arrays.toString(HealthStatus.Yellow.aliases()));
////            System.out.println(Arrays.toString(HealthStatus.Green.aliases()));
//
//
//            Boolean flag = status.equals("YELLOW") || status.equals("GREEN") ? true : false;

//            System.out.println(responseEntity);
//            System.out.println(flag);
        } catch (IOException e) {

            throw new RuntimeException(e);
        }

    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}
